package com.zbest.component.framework.pigeon.template;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

public class TemplateManager implements ApplicationContextAware {
	private static final Logger logger = LoggerFactory.getLogger(TemplateManager.class);
	
	ApplicationContext applicationContext;
	
	private static Map<String,Template> templateMap = new HashMap<String, Template>();
	
	public void setApplicationContext(ApplicationContext applicationContext)
			throws BeansException {
		this.applicationContext = applicationContext;

	}

	public ApplicationContext getApplicationContext() {
		return applicationContext;
	}

	public void registerTemplate(TemplateDescriptor templateDescriptor) throws Exception {
		
		logger.debug("registerTemplate......");
		
		List<ProcessDescriptor> plist = templateDescriptor.getProcess();
		List<Process> processList = new ArrayList<Process>();
		for (Iterator<ProcessDescriptor> iterator = plist.iterator(); iterator.hasNext();) {
			ProcessDescriptor processDescriptor = (ProcessDescriptor) iterator.next();
			Process process = new Process();
			
			List<ActionDescriptor> actionDescriptorList = processDescriptor.getAction();
			List<Action> actionList = new ArrayList<Action>();
			for (Iterator<ActionDescriptor> iterator2 = actionDescriptorList.iterator(); iterator2.hasNext();) {
				Action action = new Action();
				ActionDescriptor actionDescriptor = (ActionDescriptor) iterator2.next();
				String beanName = actionDescriptor.getBean();
				try{
					action.setBean(this.applicationContext.getBean(beanName));
				}catch(Exception e){
					logger.debug("no a bean found with:"+beanName);
					throw e;
				}
				action.setName(actionDescriptor.getName());
				action.setDesc(actionDescriptor.getDesc());
				actionList.add(action);
				process.getActionMap().put(actionDescriptor.getName(), action);
			}
			process.setActionList(actionList);
			process.setName(processDescriptor.getName());
			processList.add(process);
		}
		
		Template template = new Template(templateDescriptor.getName(),processList);
		System.out.println("------------putMap---------|"+template.getName()+"|----templateBean---|"+template.toString());
		templateMap.put(template.getName(), template);
	}
	
	public Template getTemplateByName(String name){
		return templateMap.get(name);
	}
	


}
